//
//  APPLoadingView.m
//  MobileClassPhone
//
//  Created by SL on 14-4-13.
//  Copyright (c) 2014年 cyx. All rights reserved.
//

#import "APPLoadingView.h"
#import "YCRingSpinnerView.h"
#import "CommUtls.h"
#import <Masonry/Masonry.h>
#import "YCViewConstant.h"

/**
 *  加载状态是否需要删除title
 */
#define LOADING_REMOVE_TITLE            1

#define LOADINGVIEW_GAP                 12
#define TITLE_GAP                       10
#define BUTTON_GAP                      10

typedef void (^APPCycleLoading)();

@interface APPLoadingView()
{
    UIView *contentView;
    
    //logo图片
    UIImageView *logoImage;
    
    //提示Label
    UILabel *titleLabel;
    
    //重试button
    UIButton *cycleButton;
    
    //
    YCRingSpinnerView *loading;
}

@property (nonatomic,copy) APPCycleLoading cycleBlock;
@property (nonatomic,assign) CGFloat minWidth;

- (void)startAnimating;
- (void)stopAnimating;

@end

@implementation APPLoadingView

- (void)dealloc {
#ifdef DEBUG
    NSLog(@"dealloc -- %@",[self class]);
#endif
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
        contentView = [UIView new];
        [self addSubview:contentView];
        [contentView setBackgroundColor:[UIColor clearColor]];
        [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.mas_equalTo(0);
        }];
        
        logoImage = [UIImageView new];
        [logoImage setBackgroundColor:[UIColor clearColor]];
        [contentView addSubview:logoImage];
        
        loading = [[YCRingSpinnerView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        loading.circleColor = [YCViewConstant sharedInstance].loadingColor;
        [contentView addSubview:loading];
        [loading mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(contentView.mas_centerX);
            make.top.mas_equalTo(0);
            make.width.height.mas_equalTo(40);
        }];
        
        titleLabel = [UILabel new];
        [titleLabel setBackgroundColor:[UIColor clearColor]];
        [titleLabel setTextColor:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1]];
        [titleLabel setNumberOfLines:0];
        [contentView addSubview:titleLabel];
    }
    return self;
}

- (void)showAPPLoadingView:(APPLoadingType)type
                     cycle:(void(^)())cycle
                     title:(NSString *)title
               buttonTitle:(NSString *)buttonTitle
               customImage:(NSString *)customImage {
    if (!self.minWidth) {
        self.minWidth = MIN(MIN(self.superview.frame.size.width, self.superview.frame.size.height), MIN([[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height));
        //解决自动布局下superview的宽度高度为0
        if (!self.minWidth) {
            self.minWidth = MIN([[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
        }
    }
    
    self.cycleBlock = cycle;
    [cycleButton setHidden:!(type==APP_LoadingCycle || cycle)];
    [self stopAnimating];
    
    NSString *imageName = nil;
    
    switch (type) {
        case APP_Loading:{
            //加载中
            imageName = @"buffer_image.png";
        }
            break;
        case APP_LoadingCycle:{
            
        }
            break;
        case APP_LoadingDone:{
            //加载完成，没有数据显示，不需要重新加载，友好提示
            imageName = @"connection_failed2.png";
        }
            break;
        case APP_LoadingRemove:{
            [self removeFromSuperview];
            return;
        }
            break;
        default:
            break;
    }
    
    if (type == APP_LoadingCycle || cycle) {
        //添加可重新加载的button
        NSString *cycleImageName = [YCViewConstant sharedInstance].cycleImageName;
        imageName = cycleImageName?cycleImageName:@"connection_failed2";
        
        if (!cycleButton) {
            cycleButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [contentView addSubview:cycleButton];
            cycleButton.titleEdgeInsets = [YCViewConstant sharedInstance].cycleButtontitleEdgeInsets;
            [cycleButton addTarget:self action:@selector(CycleLoading) forControlEvents:UIControlEventTouchUpInside];
        }
        
        NSString *cycleButtonImageName = [YCViewConstant sharedInstance].cycleButtonImageName;
        NSString *cycleButtonTip = [YCViewConstant sharedInstance].cycleButtonTip;
        if (cycleButtonImageName) {
            [cycleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            //有背景图片的字体一般是白色
            [cycleButton setBackgroundColor:[UIColor clearColor]];
            [cycleButton setBackgroundImage:[UIImage imageNamed:cycleButtonImageName] forState:UIControlStateNormal];
            [cycleButton setTitle:buttonTitle?buttonTitle:(cycleButtonTip?cycleButtonTip:@"刷新") forState:UIControlStateNormal];
            //有背景图片的字体一般是白色
            [cycleButton sizeToFit];
        }else{
            [cycleButton setTitleColor:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1] forState:UIControlStateNormal];
            [cycleButton setBackgroundColor:[UIColor whiteColor]];
            [cycleButton setTitle:buttonTitle?buttonTitle:(cycleButtonTip?cycleButtonTip:@"刷新") forState:UIControlStateNormal];
            [cycleButton sizeToFit];
            [cycleButton setFrame:CGRectMake(0, 0, MAX(95, cycleButton.frame.size.width+20), 37)];
            [cycleButton.layer setCornerRadius:cycleButton.frame.size.height/2];
            [cycleButton.layer setBorderColor:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1].CGColor];
            [cycleButton.layer setBorderWidth:1];
        }
    }
    
    if (type == CDELLoadingCustom) {
        imageName = customImage;
    }
    
    [logoImage setImage:[UIImage imageNamed:imageName]];
    [logoImage sizeToFit];
    
    [titleLabel setFrame:CGRectMake(0, 0, self.minWidth-40, CGFLOAT_MIN)];
    [titleLabel setText:title];
    [titleLabel sizeToFit];
    
    //整体内容高度
    CGFloat width = 0;
    CGFloat height = 0;
    CGFloat titleWidth = (title?titleLabel.frame.size.width+40:0);
    CGFloat titleHeight = (title?titleLabel.frame.size.height+TITLE_GAP:0);
    if (type == APP_Loading) {
        width = (LOADING_REMOVE_TITLE?loading.frame.size.width:MAX(loading.frame.size.width,titleWidth));
        height = (LOADING_REMOVE_TITLE?loading.frame.size.height:loading.frame.size.height+titleLabel.frame.size.height+5);
    }else if (type == APP_LoadingCycle || cycle){
        width = MAX(MAX(logoImage.frame.size.width, titleWidth), cycleButton.frame.size.width);
        height = logoImage.frame.size.height + titleHeight + (cycleButton.frame.size.height+BUTTON_GAP);
    }else{
        width = MAX(logoImage.frame.size.width, titleWidth);
        height = logoImage.frame.size.height + titleHeight;
    }
    
    if (type == APP_Loading) {
        if (title) {
            if (LOADING_REMOVE_TITLE) {
                //加载框暂时不需要显示loading文字
                [titleLabel setText:nil];
            } else {
                [titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.mas_equalTo(contentView.mas_centerX);
                    make.top.mas_equalTo(loading.mas_bottom).mas_equalTo(5);
                    make.width.mas_equalTo(titleLabel.frame.size.width);
                    make.height.mas_equalTo(titleLabel.frame.size.height);
                }];
            }
        }
        [self startAnimating];
        [logoImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(loading.mas_centerX);
            make.centerY.mas_equalTo(loading.mas_centerY);
        }];
    }else{
        [logoImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(contentView.mas_centerX);
            make.top.mas_equalTo(0);
        }];
        if (title) {
            [titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(contentView.mas_centerX);
                make.top.mas_equalTo(logoImage.mas_bottom).mas_equalTo(TITLE_GAP);
                make.width.mas_equalTo(titleLabel.frame.size.width);
                make.height.mas_equalTo(titleLabel.frame.size.height);
            }];
        }
        if (type == APP_LoadingCycle || cycle) {
            [cycleButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(contentView.mas_centerX);
                make.top.mas_equalTo(title?titleLabel.mas_bottom:logoImage.mas_bottom).mas_equalTo(BUTTON_GAP);
                make.width.mas_equalTo(cycleButton.frame.size.width);
                make.height.mas_equalTo(cycleButton.frame.size.height);
            }];
        }
    }
    
    if (!([[[UIDevice currentDevice] systemVersion] doubleValue] >= 8.0? YES : NO) && ([self.superview isKindOfClass:[UITableView class]] || [self.superview isKindOfClass:[UICollectionView class]])) {
        self.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin
								| UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
        self.frame = CGRectMake(0, 0, width, height);
        [self setCenter:CGPointMake(self.superview.frame.size.width/2, self.superview.frame.size.height/2)];
    }else{
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(width);
            make.height.mas_equalTo(height);
            make.centerX.mas_equalTo(self.superview.mas_centerX);
            make.centerY.mas_equalTo(self.superview.mas_centerY);
        }];
    }
}

//重新加载数据
- (void)CycleLoading {
    if (self.cycleBlock) {
        self.cycleBlock();
    }
}

#pragma mark - 定时器
- (void)startAnimating {
    [loading setHidden:NO];
    [loading startAnimating];
}

- (void)stopAnimating {
    [loading setHidden:YES];
    [loading stopAnimating];
}

@end
